const timeout = 4000;
let funcMap = {};
let port = chrome.runtime.connect({name: "record-connect"});

//guid
function guid() {
    return 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    let o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//执行background方法
function invoke(method, data, func) {
    let fid = guid();
    funcMap[fid] = func;
    port.postMessage({type: 'eval', fid: fid, method: method, data: data});
    setTimeout(() => {
        delete funcMap[fid];
    }, timeout);
}

//执行background回调
function invokeCallback(msg) {
    if (msg.fid) {
        let func = funcMap[msg.fid];
        if (func) {
            func(msg.data);
        }
    }
}

//供backgroud调用
function eval(msg) {
    if (msg.method && window[msg.method]) {
        let ret = window[msg.method](msg.data);
        if (ret.then) {
            ret.then(retData => {
                port.postMessage({type: 'callback', fid: msg.fid, data: retData});
            });
        } else {
            port.postMessage({type: 'callback', fid: msg.fid, data: ret});
        }
    }
}


//处理消息
function handlerMsg(msg) {
    if (msg.type == 'callback') {
        invokeCallback(msg);
    } else if (msg.type == 'eval') {
        eval(msg);
    }

}


//链接background.js
port.onMessage.addListener((msg) => handlerMsg(msg));


